package com.mmall.service;

import com.google.common.base.Preconditions;
import com.mmall.beans.Mail;
import com.mmall.beans.PageQuery;
import com.mmall.beans.PageResult;
import com.mmall.common.ExceptionError;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysUserMapper;
import com.mmall.model.SysUser;
import com.mmall.param.UserParam;
import com.mmall.util.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysUserService {

    @Resource
    private SysUserMapper mapper;
    @Resource
    private SysLogService sysLogService;

    /**
     * 添加
     * @param param
     */
    public void save(UserParam param) {
        BeanVaildator.check(param);
        if (checkTelephoneExist(param.getTelephone(),param.getId())>0){
            ExceptionError.throwError("电话已被占用");
        }
        if (checkMailExist(param.getMail(),param.getId())>0){
            ExceptionError.throwError("邮箱已被占用");
        }

        String password = PasswordUtil.randomPassword();
        password = MD5Util.encrypt("123456");
        SysUser sysUser = SysUser.builder().username(param.getUsername()).password(password).deptId(param.getDeptId()).mail(param.getMail()).telephone(param.getTelephone()).status(param.getStatus()).build();
        sysUser.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysUser.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysUser.setOperateTime(new Date());

        //通过邮箱发送密码
        Set<String> set = new HashSet<>();
        set.add(param.getMail());
        Mail mail = Mail.builder().subject("权限管理系统的登录密码").message("用户："+param.getUsername()+",你好，你的登录密码为：123456").receivers(set).build();
        MailUtil.send(mail);
        mapper.insertSelective(sysUser);
        sysLogService.saveUserLog(null,sysUser);
    }

    public void update(UserParam param) {
        BeanVaildator.check(param);
        SysUser before = mapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新用户不存在");
        if (checkTelephoneExist(param.getTelephone(),param.getId())>0){
            ExceptionError.throwError("电话已被占用");
        }
        if (checkMailExist(param.getMail(),param.getId())>0){
            ExceptionError.throwError("邮箱已被占用");
        }

        String password = PasswordUtil.randomPassword();
        password = MD5Util.encrypt("123456");
        SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).password(before.getPassword()).deptId(param.getDeptId()).mail(param.getMail()).telephone(param.getTelephone()).status(param.getStatus()).build();
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateTime(new Date());

        mapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before,after);
    }

    private int checkMailExist(String mail, Integer id) {
        return mapper.countByMail(mail,id);
    }

    private int checkTelephoneExist(String telephone, Integer id) {
        return mapper.countByTelephone(telephone,id);
    }

    public SysUser findByKeyword(String username) {
        return mapper.findByKeyword(username);
    }

    public PageResult<SysUser> getPageByDeptId(Integer deptId, PageQuery pageQuery){
        BeanVaildator.check(pageQuery);
        int count = mapper.countByDeptId(deptId);
        if (count > 0){
          List<SysUser> list = mapper.getPageByDeptId(deptId,pageQuery);
          return PageResult.<SysUser>builder().total(count).data(list).build();
        }
       return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> getAll() {
        return mapper.getAll();
    }
}
